#ifdef _WIN32
#include <windows.h>
#include <atlstr.h>
#endif

#include <node.h>
#include <v8.h>
#include <string>


using namespace std;
using namespace v8;

namespace nos{
    
	#ifdef _WIN32
	typedef struct
	{
		HWND hWnd;
		DWORD dwPid;
	}WNDINFO;

	BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam)
	{
		WNDINFO* pInfo = (WNDINFO*)lParam;
		DWORD dwProcessId = 0;
		GetWindowThreadProcessId(hWnd, &dwProcessId);

		if (dwProcessId == pInfo->dwPid)
		{
			pInfo->hWnd = hWnd;
			return FALSE;
		}
		return TRUE;
	}

	HWND GetHwndByProcessId(DWORD dwProcessId)
	{
		WNDINFO info = { 0 };
		info.hWnd = NULL;
		info.dwPid = dwProcessId;
		EnumWindows(EnumWindowsProc, (LPARAM)&info);
		return info.hWnd;
	}
	#endif
	
	
	void getDrivers(const FunctionCallbackInfo<Value>& args)
	{
		Isolate* isolate=args.GetIsolate();
        string drivers("/");
        #ifdef _WIN32
        drivers="";
	    TCHAR szBuf[100];
	    memset(szBuf, 0, 100);
	    DWORD len = GetLogicalDriveStrings(sizeof(szBuf) / sizeof(TCHAR), szBuf);
	    for (TCHAR * s = szBuf; *s; s += _tcslen(s) + 1) {
            drivers += drivers == "" ? "" : "&";
		    drivers += s;
	    }
        #endif
		args.GetReturnValue().Set(String::NewFromUtf8(isolate,drivers.c_str()));
	}
	
	void hideWindow(const FunctionCallbackInfo<Value>& args )
	{
		
		Isolate* isolate = args.GetIsolate();
		if (args.Length() < 1) {
    		// Throw an Error that is passed back to JavaScript
    		isolate->ThrowException(Exception::TypeError(
        	String::NewFromUtf8(isolate, "Wrong number of arguments")));
    		return;
  		}
		if (!args[0]->IsNumber()) {
    		isolate->ThrowException(Exception::TypeError(
        	String::NewFromUtf8(isolate, "Wrong arguments type")));
    		return;
  		}
		#ifdef _WIN32
			HWND h_win = GetHwndByProcessId(args[0]->NumberValue());
			ShowWindow(h_win, SW_HIDE);
		#endif
		return;
	}
	

	void init(Local<Object> exports,Local<Object> module)
	{
		NODE_SET_METHOD(exports,"getDrivers",getDrivers);
		NODE_SET_METHOD(exports,"hideWindow",hideWindow);
	}
    
    /*
        模块导出
    */
	NODE_MODULE(nos,init)
}
